package cc.eddic.practice.spring.jpa;


import lombok.val;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.Objects;

@Converter(autoApply = true)
public abstract class BaseCodeConverter<EnumType extends Enum<EnumType> & EnumCode> implements AttributeConverter<EnumType, Integer> {
    private final Class<EnumType> clazz;

    protected BaseCodeConverter(Class<EnumType> clazz) {
        this.clazz = clazz;
    }

    @Override
    public Integer convertToDatabaseColumn(EnumType enumType) {
        if (Objects.isNull(enumType)) {
            return null;
        }
        return enumType.getCode();
    }

    @Override
    public EnumType convertToEntityAttribute(Integer shortCode) {
        if (Objects.isNull(shortCode)) {
            return null;
        }

        return Arrays.stream(clazz.getEnumConstants())
                .filter(x -> Objects.equals(x.getCode(), shortCode))
                .findFirst()
                .orElseThrow(() -> {
                    val msg = String.format("Invalid ShortCode <%d> of type %s", shortCode, clazz.getTypeName());
                    return new IllegalArgumentException(msg);
                });
    }
}
